package com.eternal.settings;

import androidx.lifecycle.Observer;
import android.content.Context;
import android.content.Intent;
import androidx.annotation.Nullable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.RadioGroup;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.eternal.base.concat.DeviceModel;
import com.eternal.base.data.RepositoryInjection;
import com.eternal.base.global.ActivityEvent;
import com.eternal.base.global.BluetoothKey;
import com.eternal.base.global.ProgressEvent;
import com.eternal.base.router.RouterActivityPath;
import com.eternal.framework.binding.command.BindingConsumer;
import com.eternal.framework.bus.Messenger;
import com.eternal.framework.bus.RxBus;
import com.eternal.framework.component.BaseActivity;
import com.eternal.settings.databinding.ActivitySettingsBinding;
import com.eternal.widget.guqiang.SingleProgressBar;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * @author Administrator
 */
@Route(path = RouterActivityPath.Setting.PAGE_SETTING)
public class SettingActivity extends BaseActivity<ActivitySettingsBinding, SettingModel> implements SingleProgressBar.OnChangeListener{
    static final String SET_BRIGHTNESS="set brightness";
    static final String SET_TRANS_TMP="set trans tmp";
    static final String SET_TRANS_HUM="set trans hum";
    static final String SET_CALI_TMP="set cali tmp";
    static final String SET_CALI_HUM="set cali hum";


    private Disposable progressEvent;
    private boolean first;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_settings;
    }

    @Override
    public int initVariableId() {
        return BR.model;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bindingEvent();
        registerEvent();
        register();
        Intent intent=getIntent();
        byte type=intent.getByteExtra(ActivityEvent.DEVICE_TYPE, (byte)1);
        byte port = intent.getByteExtra(ActivityEvent.DEVICE_PORT,(byte)0x0);
        viewModel.init(RepositoryInjection.providerDeviceRepository(),
                intent.getStringExtra(ActivityEvent.DEVICE_MAC)
                ,port
                ,intent.getStringExtra(ActivityEvent.DEVICE_TIME), type);
        initView(type,port);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterEvent();
        unregister();
    }

    private void registerEvent(){
        Messenger messenger=Messenger.getDefault();
        messenger.register(this, SET_BRIGHTNESS, Byte.class, new BindingConsumer<Byte>() {
            @Override
            public void call(Byte type) {
                int id;
                switch (type){
                    case 0x1:
                        id=R.id.rb_low;
                        break;
                    case 0x2:
                        id=R.id.rb_medium;
                        break;
                    case 0x3:
                        id=R.id.rb_height;
                        break;
                    case (byte)0xa2:
                        id=R.id.rb_a2;
                        break;
                    default:
                        id=R.id.rb_a3;
                }
                binding.brightRadioGroup.check(id);
            }
        });

        messenger.register(this, SET_TRANS_TMP, Byte.class, new BindingConsumer<Byte>() {
            @Override
            public void call(Byte size) {
                binding.spbTemperature.setShowText(size);
            }
        });

        messenger.register(this, SET_TRANS_HUM, Byte.class, new BindingConsumer<Byte>() {
            @Override
            public void call(Byte size) {
                binding.spbHum.setShowText(size);
            }
        });

        messenger.register(this, SET_CALI_TMP, Byte.class, new BindingConsumer<Byte>() {
            @Override
            public void call(Byte size) {
                binding.spbCalibrationTemperature.setShowText(size);
            }
        });

        messenger.register(this, SET_CALI_HUM, Byte.class, new BindingConsumer<Byte>() {
            @Override
            public void call(Byte size) {
                binding.spbCalibrationHumidity.setShowText(size);
            }
        });
    }

    private void unregisterEvent(){
        Messenger.getDefault().unregister(this);
    }

    private void register(){
        progressEvent=RxBus.getDefault().toObservable(ProgressEvent.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ProgressEvent>() {
                    @Override
                    public void accept(ProgressEvent event) throws Exception {
                        if(event.Statue==ProgressEvent.START){
                            binding.toolBar.startProgress();
                        }else if(event.Statue==ProgressEvent.END){
                            binding.toolBar.endProgress(event.callback);
                        }
                    }
                });
    }

    private void unregister(){
        if(progressEvent!=null){
            progressEvent.dispose();
            progressEvent=null;
        }
    }

    private void bindingEvent(){
        binding.brightRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_low) {
                    viewModel.brightness = 1;
                } else if (checkedId == R.id.rb_medium) {
                    viewModel.brightness = 2;
                } else if (checkedId == R.id.rb_height) {
                    viewModel.brightness = 3;
                } else if (checkedId == R.id.rb_a2) {
                    viewModel.brightness = (byte) 0xa2;
                } else {
                    viewModel.brightness = (byte) 0xa3;
                }
            }
        });

        binding.spbTemperature.setOnChangeListener(this);
        binding.spbHum.setOnChangeListener(this);
        binding.spbCalibrationTemperature.setOnChangeListener(this);
        binding.spbCalibrationHumidity.setOnChangeListener(this);

        viewModel.isEdit.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean result) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if(result==Boolean.FALSE){
                    binding.editName.setEnabled(true);
                    binding.editName.setFocusable(true);
                    binding.editName.setFocusableInTouchMode(true);
                    if (imm != null) {
                        binding.editName.requestFocus();
                        imm.showSoftInput(binding.editName, 0);
                        binding.editName.setSelection(binding.editName.getText().length());
                    }
                }else{
                    binding.editName.clearFocus();
                    binding.editName.setEnabled(false);
                    if (!first) {
                        first = !first;
                        return;
                    }
                    if (TextUtils.isEmpty(binding.editName.getText())) {
                        viewModel.showEmptyDialog();
                    }
                }
            }
        });

        viewModel.isDegree.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean result) {
                if(result){
                    binding.spbTemperature.setModeType(SingleProgressBar.Type.TRANSITION_TEMPERATURE_C);
                    binding.spbCalibrationTemperature.setModeType(SingleProgressBar.Type.CALIBRATION_TEMPERATURE_C);
                }else{
                    binding.spbTemperature.setModeType(SingleProgressBar.Type.TRANSITION_TEMPERATURE_F);
                    binding.spbCalibrationTemperature.setModeType(SingleProgressBar.Type.CALIBRATION_TEMPERATURE_F);
                }
            }
        });
    }

    private void initView(byte type,byte port){
        if(type == BluetoothKey.DEVICE_TYPE_C || type == BluetoothKey.DEVICE_TYPE_C1 || type == BluetoothKey.DEVICE_TYPE_C2){
            binding.vTransition.setVisibility(View.GONE);
            binding.vTransitionHum.setVisibility(View.GONE);
            binding.rlTransition.setVisibility(View.GONE);
            binding.rlTransitionHum.setVisibility(View.GONE);
            binding.rlDeviceBrightness.setVisibility(View.GONE);
        }else if(type== BluetoothKey.DEVICE_TYPE_B){
            binding.tvTransition.setText(R.string.setting_buffer_temperature);
            binding.tvTransitionDes.setText(R.string.setting_buffer_temperature_des);
            binding.tvTransitionHum.setText(R.string.setting_buffer_humidity);
            binding.tvTransitionHumDes.setText(R.string.setting_buffer_humidity_des);
        }
        if (port == 0) {
            binding.tvMaster.setVisibility(View.GONE);
        } else {
            binding.tvDelete.setVisibility(View.GONE);
            binding.vTransitionHum.setVisibility(View.GONE);
            binding.llContainer.removeView(binding.llTransition);
            binding.llContainer.addView(binding.llTransition,binding.llContainer.indexOfChild(binding.tvMaster));
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event){
        if(event.getKeyCode()==KeyEvent.KEYCODE_ENTER&&event.getAction()==KeyEvent.ACTION_UP){
            viewModel.onEdit.execute();
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public void onBackPressed() {
        viewModel.onBack.execute();
    }

    @Override
    public void onChange(View view, int size) {
        int id = view.getId();
        if (id == R.id.spb_temperature) {
            viewModel.transTmp = (byte) size;
            viewModel.transHum = (byte) size;
        } else if (id == R.id.spb_hum) {
            viewModel.transHum = (byte) size;
        } else if (id == R.id.spb_calibration_temperature) {
            viewModel.caliTmp = (byte) size;
        } else if (id == R.id.spb_calibration_humidity) {
            viewModel.caliHum = (byte) size;
        }
    }

    @Override
    public void onDown() {

    }

    @Override
    public void onEnd() {

    }


}
